package com.zhuqiao.tm.aspect;

import com.zhuqiao.tm.annotation.GlobalTransactional;
import com.zhuqiao.tm.transactional.MyTransaction;
import com.zhuqiao.tm.transactional.MyTransactionManager;
import com.zhuqiao.tm.transactional.TransactionType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class GlobalTransactionalAspect implements Ordered {

    @Around("@annotation(com.zhuqiao.tm.annotation.GlobalTransactional)")
    public void invoke(ProceedingJoinPoint joinPoint){
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        GlobalTransactional annotation = method.getAnnotation(GlobalTransactional.class);

        String groupId = "";
        if(annotation.isStart()){
            //创建事务组，提交事务组
            groupId = MyTransactionManager.createTransactionGroup();
        }else {
            //如果不是第一个事务，则从TransactionManager中获取groupId
            groupId = MyTransactionManager.getCurrentGroupId();
        }

        //子事务数量
        MyTransactionManager.setTransactionCount(annotation.total());

        //创建事务
        MyTransaction myTransaction = MyTransactionManager.createTransaction(groupId);
        try {
            joinPoint.proceed();//spring原来的逻辑
            myTransaction.setTransactionType(TransactionType.commit);
        } catch (Throwable throwable) {
            myTransaction.setTransactionType(TransactionType.rollback);
            throwable.printStackTrace();
        }
        //添加事务到事务组
        MyTransactionManager.addTransaction(myTransaction, annotation.isEnd());
    }

    @Override
    public int getOrder() {
        return 999;
    }
}
